//
//  DBNetworkTool.swift
//  大波微博swift
//
//  Created by 大波 on 16/2/28.
//  Copyright © 2016年 zhaojin. All rights reserved.
//

import UIKit
import AFNetworking

enum DBNetworkError: Int {
    
    case DBNetworkEmptyAccess_token = 0
    
    case DBNetworkEmptyUid = 1
    
    case DBNetworkLoding = 2
    
    var errorMessage: String {
        
        get {
            
            switch self {
                
            case DBNetworkEmptyAccess_token: return "Access_token 没有值"
                
            case DBNetworkEmptyUid: return "uid 没有值"
                
            case DBNetworkLoding: return "数据正在加载中"
                
            }
        }
    }
    
    func error() -> NSError {
        
        return NSError(domain: "cn.itcast.net", code: self.rawValue, userInfo: ["errorMessage" : self.errorMessage])
    }
    
}

class DBNetworkTool: NSObject {
    
    let AFNManager: AFHTTPSessionManager
    
    static let shareNetworkTool: DBNetworkTool = DBNetworkTool()
    
    /// 重定义完成回调的闭包类型
    typealias finishedClosure = (finish: [String : AnyObject]?, error: NSError?) -> ()
    
    /// 是否正在加载微博数据标识符
    var isloadStatuseData: Bool = false
    
    private override init() {
        
        let baseURL = NSURL(string: "https://api.weibo.com/")
        
        AFNManager = AFHTTPSessionManager(baseURL: baseURL)
        
        /// AFN响应序列化解析器没有 text/plain 这个类型
        // 添加 text/plain
        AFNManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    
    /// App Key
    let client_id = "13532587"
    
    /// 回调地址
    let redirect_uri = "http://www.baidu.com/"
    
    /// 授权基地址
    let oauthURL = "https://api.weibo.com/oauth2/authorize"
    
    /// 获取oauth授权地址
    func oauthLoginURL() -> NSURL {
        
        let URLString = oauthURL + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        
        return NSURL(string: URLString)!
    }
    
    /// 获取token
    func loadToken(code: String, accessTokenFinishClosure: ([String : AnyObject]?, NSError?) -> ()) {
        
        let tokenURL = "https://api.weibo.com/oauth2/access_token"
        
        // 参数字典
        let parameters = [
            
            "client_id" : client_id,
            
            "client_secret" : "2479cb728287fe6229f57cd8150be05e",
            
            "grant_type" : "authorization_code",
            
            "code" : code,
            
            "redirect_uri" : redirect_uri
        ]
        
        networkRequest("POST", URLString: tokenURL, parameters: parameters, progress: nil, finish: accessTokenFinishClosure)
    }
    
    /// 加载用户信息
    func loadUserInfo(finish: finishedClosure) {
        
        guard let uid = DBUserAccountViewModel.shareUserAccountViewModel.userAccount?.uid else {
            
            let error = DBNetworkError.DBNetworkEmptyUid.error()
            
            finish(finish: nil, error: error)
            
            return
        }
        
        let userInfoURL = "https://api.weibo.com/2/users/show.json"
        
        let parameters = [
            
            "uid" : uid
        ]
        
        networkRequest("GET", URLString: userInfoURL, parameters: parameters, progress: nil, finish: finish)
    }
    
    /// 加载微博数据
    func loadStatuses(since_id: Int, max_id: Int, finish: finishedClosure) {
        
        // 加载本地数据开关
        let debug = true
        
        if debug {
            
            loadLocalData(finish)
            
            return
        }
        
        let URLString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        /*
        
        since_id	false	int64	若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
        max_id	false	int64	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
        
        */
        
        var parameters = [String : AnyObject]()
        
        if since_id > 0 {
            
            parameters["since_id"] = since_id
            
        } else if max_id > 0 {
            
            parameters["max_id"] = max_id
        }
        
        if isloadStatuseData {
            
            let error = DBNetworkError.DBNetworkLoding.error()
            
            finish(finish: nil, error: error)
            
            return
        }
        
        isloadStatuseData = true
        
        // 调试上拉刷新重复
//        parameters["count"] = 2
        
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), { () -> Void in
//
//            self.networkRequest("GET", URLString: URLString, parameters: parameters, progress: nil, finish: finish)
//
//            self.isloadStatuseData = false
//        })
        
        networkRequest("GET", URLString: URLString, parameters: parameters, progress: nil, finish: finish)
        
        isloadStatuseData = false
    }
    
    /// 加载本地数据
    private func loadLocalData(finish: finishedClosure) {
        
        let path = NSBundle.mainBundle().pathForResource("localData", ofType: "json")
        
        let data = NSData(contentsOfFile: path!)
        
        let dic = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! [String : AnyObject]
        
        finish(finish: dic, error: nil)
    }
    
    
    // MARK: - 封装AFN私有方法
    
    /// 获取请求的封装第三方网络工具
    private func networkRequest(requestMethod: String, URLString: String, var parameters: [String : AnyObject]?, progress: ((NSProgress) -> Void)?, finish: finishedClosure) {
        
        // 当没有传参数的时候创建字典
        if parameters == nil {
            
            parameters = [String : AnyObject]()
        }
        
        // GET请求走这个判断
        if requestMethod == "GET" {
            
            // 守卫 判断token值
            guard let access_token = DBUserAccountViewModel.shareUserAccountViewModel.userAccount?.access_token else {
                
                let error3 = DBNetworkError.DBNetworkEmptyAccess_token.error()
                
                finish(finish: nil, error: error3)
                
                return
            }
            
            // 添加 access_token 参数
            parameters!["access_token"] = access_token
            
            AFNManager.GET(URLString, parameters: parameters, progress: progress, success: { (_, response) -> Void in
                
                finish(finish: response as? [String : AnyObject], error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                    finish(finish: nil, error: error)
            })
        }
        
        // POST请求
        if requestMethod == "POST" {
            
            AFNManager.POST(URLString, parameters: parameters, progress: progress, success: { (_, response) -> Void in
                
                finish(finish: response as? [String : AnyObject], error: nil)
                
                }, failure: { (_, error) -> Void in
                    
                    finish(finish: nil, error: error)
            })
        }
    }
}











